package com.xsq.wifi.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;

/**
 * 编写人：李振德
 * 创建时间：2025/6/9
 */
public class VideoUploader {

    public static void uploadRawFile(File file, PersistentConnection connection, UploadCallback callback) {
        new Thread(() -> {
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[64 * 1024]; // 64KB分块
                int bytesRead;
                long totalSent = 0;

                // 直接循环读取文件并发送原始数据
                while ((bytesRead = fis.read(buffer)) != -1) {
                    connection.sendRequest(
                            ProtocolConstants.CMD_FILETRANS_DATA, // 唯一命令字
                            Arrays.copyOf(buffer, bytesRead)      // 原始数据块
                    );

                    // 更新进度
                    totalSent += bytesRead;
                    callback.onProgress((int) (totalSent * 100 / file.length()));
                }

                callback.onSuccess(); // 传输完成

            } catch (Exception e) {
                callback.onFailure(e.getMessage());
            }
        }).start();
    }

    public interface UploadCallback {
        void onProgress(int percent);
        void onSuccess();
        void onFailure(String error);
    }
}
